package org.ajc.gift.exception;


import org.ajc.gift.util.AjaxResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestControllerAdvice //拦截系统产生的异常
public class GlobalExceptionHandler {

    /*
        捕获指定的异常
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult systemException(Exception e){
        e.printStackTrace();
        return AjaxResult.me().setCode(ResponseCode.RESPONSE_CODE_500.getCode())
                    .setMessage(ResponseCode.RESPONSE_CODE_500.getMsg());
    }
    /*
        针对主动抛出的异常进行异常处理
     */
    @ExceptionHandler(BusinessException.class)
    public AjaxResult businessException(BusinessException e){
        e.printStackTrace();
        return AjaxResult.me().setCode(e.getCode())
                .setMessage(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult jsr303Exception(MethodArgumentNotValidException e){
        Map map = new HashMap();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        for (FieldError error : fieldErrors) {
            map.put(error.getField(),error.getDefaultMessage());
        }
        return AjaxResult.me().setCode(ResponseCode.RESPONSE_CODE_400.getCode())
                .setMessage(ResponseCode.RESPONSE_CODE_400.getMsg())
                .setResultObj(map);
    }
}
